<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #pagination>
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="timeBetween">
              <el-date-picker
                :placeholder="$t('时间选择')"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                v-model="queryParams.timeBetween"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')"
                type="datetimerange"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="type">
              <el-select :placeholder="$t('账单类型')" clearable v-model="queryParams.type" @change="handleQuery">
                <el-option
                  v-for="item in pay_type_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <!-- 是否结账 -->
            <!-- paid 付款 1 未付款 0 -->
            <el-form-item prop="paid">
              <el-select :placeholder="$t('是否结账')" clearable v-model="queryParams.paid" @change="handleQuery">
                <el-option :label="$t('是')" :value="1" />
                <el-option :label="$t('否')" :value="0" />
              </el-select>
            </el-form-item>
            <!-- 租户 -->
            <el-form-item prop="distrId">
              <el-select :placeholder="$t('租户')" clearable v-model="queryParams.distrId" @change="handleQuery">
                <el-option v-for="item in distrList" :label="item.name" :value="item.distrId" :key="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item prop="skuNo">
              <el-input :placeholder="$t('sku编号')" @keyup.enter.native="handleQuery" v-model="queryParams.skuNo" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="orderNo">
              <el-input :placeholder="$t('订单号')" @keyup.enter.native="handleQuery" v-model="queryParams.orderNo" />
            </el-form-item>
            <el-form-item prop="packageNo">
              <el-input :placeholder="$t('包裹号')" @keyup.enter.native="handleQuery" v-model="queryParams.packageNo" />
            </el-form-item>
            <el-form-item prop="payType">
              <el-select :placeholder="$t('结账类型')" clearable v-model="queryParams.payType" @change="handleQuery">
                <el-option
                  v-for="item in closing_type_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="packageNo">
              <el-select :placeholder="$t('支付渠道')" clearable v-model="queryParams.payChannel" @change="handleQuery">
                <el-option
                  v-for="item in pay_channel_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-button size="mini" v-hasPermi="['distribution:bill:batchBillPayInfo']" @click="submitFormDataPayList">
          <!-- 付款 -->
          {{ $t('付款') }}
        </el-button>
      </template>
    </PageSearch>
    <el-table
      :height="calTableHeight()"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      ref="TableRef"
      :data="tableData"
      row-key="menuId"
    >
      <el-table-column type="selection" :selectable="selectable" align="center" fixed="left" />
      <!-- 租户 -->
      <el-table-column :label="$t('租户')" align="center" show-overflow-tooltip prop="distrName" width="200" />
      <el-table-column :label="$t('店铺/平台')" align="center" show-overflow-tooltip prop="xxx" width="200">
        <template slot-scope="{ row }">
          <div>{{ row.shopName }}</div>
          <div>{{ row.shopTypeName }}</div>
        </template>
      </el-table-column>
      <!-- 账单类型 1订单批次sku费用，2批次订单快递费用，3订单批次捆包费用，4订单批次手续费用，5再发货sku费用，6再发货快递费用，7再发货捆包费用，8提前付款，9阶段付款 -->
      <el-table-column :label="$t('账单类型')" align="center" show-overflow-tooltip prop="type" width="200">
        <template slot-scope="{ row }">
          <span :style="{ color: $randomColor(row.type) }">
            {{ handlePayType(row.type) }}
          </span>
        </template>
      </el-table-column>
      <!-- 应付款金额 -->
      <el-table-column align="center" show-overflow-tooltip :label="$t('应付款金额')" prop="payAmount">
        <!-- 应付款金额币种 1RMB 2JPY 3USD -->
        <template slot-scope="{ row }">
          <span v-if="row.paid == 1" @click="handlePayDetail(row)" style="cursor: pointer; color: blue">
            {{ row.payAmount | thousand }}
            <span v-if="row.payCurrency == 1">RMB</span>
            <span v-if="row.payCurrency == 2">JPY</span>
            <span v-if="row.payCurrency == 3">USD</span>
          </span>

          <span v-else>
            {{ row.payAmount | thousand }}
            <span v-if="row.payCurrency == 1">RMB</span>
            <span v-if="row.payCurrency == 2">JPY</span>
            <span v-if="row.payCurrency == 3">USD</span>
          </span>
        </template>
      </el-table-column>
      <!-- 人民币对日汇率 -->
      <el-table-column align="center" show-overflow-tooltip prop="rmbRate" :label="$t('人民币对日汇率')" width="80" />
      <!-- 美元对日汇率 -->
      <el-table-column align="center" show-overflow-tooltip prop="usdRate" :label="$t('美元对日汇率')" width="80" />

      <!-- 结账类型 1:线上支付 2:手动结账 -->
      <el-table-column align="center" show-overflow-tooltip prop="payType" :label="$t('结账类型')">
        <template slot-scope="{ row }">
          <div :style="{ color: $randomColor(row.payType) }">
            {{ handleType(row.payType, closing_type_list) }}
          </div>
        </template>
      </el-table-column>

      <!-- 支付渠道 -->
      <el-table-column align="center" show-overflow-tooltip prop="payChannel" :label="$t('支付渠道')">
        <template slot-scope="{ row }">
          {{ handleType(row.payChannel, pay_channel_list) }}
        </template>
      </el-table-column>
      <el-table-column align="center" width="80" prop="offlineStatus" :label="$t('线下支付审核状态')">
        <template slot-scope="{ row }">
          <span v-if="row.offlineStatus == 1">
            <!-- 待审核 -->
            {{ $t('审核中') }}
          </span>
          <span style="color: green" v-if="row.offlineStatus == 2">
            <!-- 审核通过 -->
            {{ $t('已确定') }}
          </span>
          <span style="color: red" v-if="row.offlineStatus == 3">
            <!-- 审核不通过 -->
            {{ $t('取消') }}
          </span>
        </template>
      </el-table-column>
      <!-- 账单生成时间 -->
      <el-table-column align="center" show-overflow-tooltip prop="createTime" :label="$t('账单生成时间')" />
      <!-- 是否结账 -->
      <el-table-column align="center" show-overflow-tooltip prop="paid" :label="$t('是否结账')">
        <template slot-scope="{ row }">
          <span v-if="row.paid == 1" style="color: green">
            <!-- 已支付 -->
            {{ $t('是') }}
          </span>
          <span v-if="row.paid == 0" style="color: red">
            <!-- 未支付 -->
            {{ $t('否') }}
          </span>
        </template>
      </el-table-column>
      <!-- 支付日期 -->
      <el-table-column align="center" show-overflow-tooltip prop="payTime" :label="$t('支付日期')" width="150" />
      <!-- 支付金额修改备注 -->
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="payAmountUpdateRemark"
        :label="$t('支付金额修改备注')"
      />
      <!-- 操作 -->
      <el-table-column align="center" fixed="right" :label="$t('操作')">
        <template slot-scope="{ row }">
          <el-button v-hasPermi="['distribution:bill:query']" type="text" size="small" @click="handleDetail(row)">
            <!-- 查看 -->
            {{ $t('查看') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pageTotal > 0"
      :total="pageTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <Detail
      :FormData="FormData"
      :type="detailInfo.type"
      :show.sync="detailInfo.show"
      :title="detailInfo.title"
      :data="detailInfo.data"
    />
    <PayInforMation :show.sync="PayInforMationShow" :FormData="FormData" :handlePayType="handlePayType" />
    <!-- 支付弹框 支付详情-->
    <Pay ref="payForm" :show.sync="pay.show" :formData="pay.formData" @getList="getList" @updataPayType="updataPayType">
      <template #default="{ handlePayMethod }">
        <div style="margin: 20px 0" v-hasPermi="['distribution:bill:sellerBatchBillOfflinePay']">线下支付:</div>
        <div class="payContentOffline" v-hasPermi="['distribution:bill:sellerBatchBillOfflinePay']">
          <el-button
            :class="{ 'is-active': offlinePayTypestr == 1 }"
            @click="offlinePayType(1, handlePayMethod, 'offlineCash')"
            >现金支付</el-button
          >
          <el-button
            :class="{ 'is-active': offlinePayTypestr == 2 }"
            @click="offlinePayType(2, handlePayMethod, 'offlineTransfer')"
            >银行卡转账</el-button
          >
        </div>
      </template>
    </Pay>
  </div>
</template>

<script>
import Pay from '@/components/Pay/index.vue'

import {
  batchBillPayHand,
  batchBillPayInfo,
  billList,
  getBillDetails,
  getDistrList,
  sellerBatchBillOfflinePay,
} from '@/api/bill/seller'
import { calcFinallyAmount, toPay } from '@/api/distribution/sku/sellerApplicationList'
import { useDict } from '@/utils/useDict'
import Detail from './components/detail.vue'
import PayInforMation from './components/payInforMation.vue'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'Seller',
  components: {
    Detail,
    PayInforMation,
    Pay,
  },
  data() {
    return {
      PayInforMationShow: false,
      /**@type{*} */
      offlinePayTypestr: '', //支付方式
      selectPayChannel: '',
      payChannelInfo: {
        businessType: '',
        businessId: '',
        orderAmount: '',
        rmbOrderAmount: '',
        usdOrderAmount: '',
        attach: '',
        payBillNum: null,
        payChannel: '',
        handingFee: '',
      },
      pay: {
        show: false,
        formData: {},
      },
      FormData: {},
      showSearch: false,
      /**
       * 租户列表
       */
      distrList: [],
      payStatus: false,
      payTypeList: [],
      payFormData: {},
      cloudProductPay: false,
      /**提前付款数据列表 */
      anticipatedPaymentList: [],
      /**详情信息 */
      detailInfo: {
        /**显示详情 */
        show: false,
        type: '',
        title: '',
        data: [],
        query: {},
      },

      /**
       * 支付类型字典
       */
      pay_type_list: [],
      /**
       * 支付渠道
       */
      pay_channel_list: [],
      /**
       * 结账类型
       */
      closing_type_list: [],
      tableData: [],
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        timeBetween: [],
        pageNum: 1,
        pageSize: 10,
        type: '',
      },
    }
  },
  created() {
    this.getList()
    useDict('pay_type').then(({ pay_type }) => (this.pay_type_list = pay_type))
    useDict('pay_channel').then(({ pay_channel }) => (this.pay_channel_list = pay_channel))
    useDict('closing_type').then(({ closing_type }) => (this.closing_type_list = closing_type))
    this.getDistrList()
  },
  methods: {
    handleType(type, list) {
      const index = list.findIndex((i) => i.dictValue == type)
      return list[index]?.dictLabel
    },
    /**账单支付详情 */
    handlePayDetail(row) {
      this.PayInforMationShow = true
      this.FormData = row
    },
    updataPayType(selectPayChannel) {
      if (selectPayChannel) {
        this.offlinePayTypestr = selectPayChannel == 'offlineCash' ? 1 : 2
        let that = this
        this.$modal
          .confirm(
            `是否确认${this.offlinePayTypestr == 1 ? '现金支付' : that.offlinePayTypestr == 2 ? '银行卡转账' : ''}支付`,
          )
          .then(function () {
            return sellerBatchBillOfflinePay({
              id: that.payFormData.businessId,
              offlinePayType: that.offlinePayTypestr,
            })
          })
          .then(() => {
            this.$message({ type: 'success', message: '操作成功' })
            this.pay.show = false
            this.getList()
          })
      } else {
        this.offlinePayTypestr = ''
      }
    },
    /**线下支付方式 */
    offlinePayType(offlinePayType, handlePayMethod, payTypeStr) {
      this.offlinePayTypestr = offlinePayType
      handlePayMethod({ payChannel: payTypeStr })
    },
    /**
     * 获取租户
     */
    getDistrList() {
      getDistrList().then((res) => {
        this.distrList = res.rows
      })
    },
    selectable(row) {
      if (row.paid == 1 || row.offlineStatus !== null) {
        return false
      } else {
        return true
      }
    },
    /**线下支付 */
    confirmPayment() {
      this.$confirm(this.$t('确认支付'), this.$t('提示'), { type: 'warning' }).then(() => {
        batchBillPayHand({ id: this.payFormData.businessId }).then((res) => {
          const { code, data, msg } = res
          if (code == 200) {
            this.$message({ type: 'success', message: msg })

            this.cloudProductPayCancel()
          }
        })
      })
    },
    /**
     * 去支付
     */
    handleGoPay() {
      this.payStatus = !this.payStatus
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      let payData = {
        // businessType: this.payFormData.businessType,
        // businessId: this.payFormData.businessId,
        // payChannel: data.payChannel,
        // orderAmount: this.payFormData.orderAmount,
        // description: '',
        // attach: this.payFormData.attach,
        // payPayDescription: [],
        ...this.payChannelInfo,
      }
      toPay(payData)
        .then((res) => {
          loading.close()
          window.open(res.data.pay_url)
          setTimeout(() => {
            this.getList()
          }, 1000)
        })
        .catch((e) => {
          loading.close()
        })
    },
    cloudProductPayCancel() {
      this.payStatus = false
      this.cloudProductPay = !this.cloudProductPay
      this.getList()
    },
    /**提前付款选择 */
    handleSelectionChange(value) {
      this.anticipatedPaymentList = value
    },
    // 卖家批量账单提前付款
    submitFormDataPayList() {
      if (this.anticipatedPaymentList.length > 0) {
        let iDFromlList = []
        this.anticipatedPaymentList.forEach((item) => iDFromlList.push(item.id))
        // 获取支付数据
        batchBillPayInfo({ idList: iDFromlList }).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.payFormData = res.data
            // this.cloudProductPay = true
            this.pay.show = true
            this.pay.formData = res.data
          }
        })
      } else {
        this.$message.error(this.$t('请选择账单'))
      }
    },
    /**获取选择支付方式的支付详情 */
    getPayDetails() {},
    handleDetail(row) {
      // console.log(` ==>`, JSON.parse(JSON.stringify(row)));
      // console.log(` ==>`, JSON.parse(JSON.stringify(row)).type);
      const { id, type } = row
      getBillDetails(id).then((res) => {
        const { code, data } = res
        this.FormData = data
        if (code === 200) {
          this.detailInfo.show = true
          this.detailInfo.title = this.handlePayType(type)
          this.detailInfo.type = type

          this.detailInfo.data = []
          switch (type) {
            case 8 /**提前付款 type=8 */:
              data.sellerApplyVo.remark = data.remark
              this.detailInfo.data = [data.sellerApplyVo]
              break
            case 9 /**阶段付款 type=9 */:
              this.detailInfo.data = data.phaseBillData
              break
            case 10 /**订单批次sku费用 type=10 */:
              this.detailInfo.data = [
                {
                  batchBaleFee: data.batchBaleFee,
                  batchExpressFee: data.batchExpressFee,
                  batchHandlingFee: data.batchHandlingFee,
                  batchSkuWaitPayTotal: data.batchSkuWaitPayTotal,
                },
              ]
              break
            case 11 /**续费充值 type=11 */:
              let rechargeRecord = JSON.parse(data.remark)
              rechargeRecord.payAmount = data.payAmount
              this.detailInfo.data = [rechargeRecord]
              break

            case 12 /**卖家充值积分 type=12 */:
              this.detailInfo.data = [data]
              break
            case 13 /**代做模板积分付款 type=13 */:
              this.detailInfo.data = data.skuTempProxyDetails
              break
            case 14 /**卖家充值积分 type=14 */:
              this.detailInfo.data = data.skuTempProxyDetails
              break
            default:
              break
          }
        }
      })
    },
    handlePayType(type) {
      const index = this.pay_type_list.findIndex((i) => i.dictValue == type)
      if (index > -1) return this.pay_type_list[index].dictLabel
    },
    // handlePayTypeColor(type) {
    //   switch (type) {
    //     case 1:
    //       return '#32CCBC'
    //     case 2:
    //       return '#F6416C'
    //     case 3:
    //       return '#28C76F'
    //     case 4:
    //       return '#F55555'
    //     case 5:
    //       return '#9708CC'
    //     case 6:
    //       return '#736EFE'
    //     case 7:
    //       return '#D939CD'
    //     case 8:
    //       return '#3CD500'
    //     case 9:
    //       return '#00EAFF'

    //     default:
    //       return '#7367F0'
    //   }
    // },

    /** 查询菜单列表 */
    getList() {
      this.loading = true
      const params = JSON.parse(JSON.stringify(this.queryParams))
      const { timeBetween } = params
      const startTime = timeBetween ? timeBetween[0] : ''
      const endTime = timeBetween ? timeBetween[1] : ''
      delete params.timeBetween
      const data = {
        ...params,
        startTime,
        endTime,
      }
      billList(data).then((res) => {
        this.tableData = res.rows
        this.pageTotal = res.total
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.keys(this.queryParams).forEach((key) => (this.queryParams[key] = ''))
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
.payMessage {
  text-align: center;
  font-size: 16px;
  color: black;
  font-weight: 700;
  margin-bottom: 10px;
}

.payAllData {
  // height: 250px;
}
.payContentOffline {
  display: flex;
  & > :first-child {
    margin: 0 40px 0 30px;
  }
}
.payTitle {
  font-size: 24px;
  font-weight: 700;
  width: 100%;
  text-align: center;
  margin-bottom: 20px;

  color: black;
}

.payList {
  padding: 5px;
  cursor: pointer;
  border-radius: 10px;
  overflow: hidden;
  margin-right: 5px;
}

.payContent {
  padding: 5px 0;
  display: flex;
  justify-content: space-around;
  &-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.adjustment {
  border-radius: 2px;
  padding: 4px;
  background-color: #e1eafc;
}

.goods {
  &-img {
    &-box {
      position: relative;
    }

    &-mini {
      height: 50px;
      border-radius: 3px;

      &:hover {
        & + .goods-img-big {
          display: block;
        }
      }
    }

    &-big {
      // display: none;
      position: absolute;
      z-index: 100;
      top: -180px;
      left: 0;
      transform: translate(0, 70px);
      width: 200px;
      height: 200px;
      border-radius: 3px;
    }
  }
}

.bigImg {
  border-radius: 3px;
  z-index: 10;
  position: fixed;
  width: 200px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
